package com.superlc.ssm.modular.sys.controller;

import com.superlc.ssm.common.util.ProjectUtils;
import com.superlc.ssm.common.util.RedisTemplateUtils;
import com.superlc.ssm.common.util.ResponseEntity;
import com.superlc.ssm.common.util.ResponseUtils;
import com.superlc.ssm.core.shiro.util.ShiroKit;
import com.superlc.ssm.modular.sys.model.UserInfo;
import com.superlc.ssm.modular.sys.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @ProjectName: ssm$
 * @Package: com.superlc.ssm.modular.sys.controller$
 * @ClassName: UserInfoController$
 * @Description: 用于用户的登陆注册 信息修改等操作
 * @Author: super
 * @CreateDate: 2018/8/15$ 13:09$
 * @UpdateUser: 更新者
 * @UpdateDate: 2018/8/15$ 13:09$
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@Controller
public class UserInfoController {


    @Resource
    private UserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate ;


    @Autowired
    private RedisTemplateUtils redisUtils ;

    private static Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    @RequestMapping("/")
    public String  toIndexPage(){
        if(ShiroKit.isAuthenticated() ||ShiroKit.getUser()!=null){
            logger.info("用户已经登录或者rememberMe，直接跳到index.");
            return "index";
        }else{
            logger.info("没有登陆信息！重定向到登陆页面！");
            return "redirect:/login";
        }

    }

    @RequestMapping("/index")
    public String  toIndex(){
        return "index";
    }

    /**
     * 点击登陆操作
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String  loginValidate(String username, String password,Boolean rememberMe, HttpServletRequest request){

        if(rememberMe==null){
            rememberMe=false ;
        }
        //判断是否登陆
        if (ShiroKit.isAuthenticated() ||ShiroKit.getUser()!=null) {
            return "redirect:/index";
        }
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password,rememberMe);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
//            UserInfo user = (UserInfo) subject.getPrincipal();
            // 执行到这里说明用户已登录成功
            return "redirect:/index";
        } catch (DisabledAccountException e) {
            request.setAttribute("msg", "账户已被禁用");
        } catch (AuthenticationException e) {
            request.setAttribute("msg", "用户名或密码错误");
        }
        return "/login";

    }

    @RequestMapping(value="/login",method = RequestMethod.GET)
    public String  toLoginPage(){
        if(ShiroKit.isAuthenticated() ||ShiroKit.getUser()!=null){
            return "index";
        }else{
            return "login";
        }
    }

    @RequestMapping("/userInfo")
    public String toUserInfoPage(){
        return "userInfo";
    }

    @RequestMapping("/logout")
    public  String logout(HttpSession session){
        session.removeAttribute("userInfo");
        return "index";
    }
    @RequestMapping("/reg")
    public String registerPage(UserInfo userInfo) {
        return "register";
    }
    @ResponseBody
    @RequestMapping("/register")
    public String register(UserInfo userInfo){
        if(userInfoService.getOnlyUserinfoByUserName(userInfo.getUsername())!=null){
            return "用户已存在";
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        userInfo.setSalt(uuid);
        userInfo.setPassword(ProjectUtils.hashCredentials("MD5",userInfo.getPassword(),userInfo.getCredentialsSalt(),2).toString());
        int result = userInfoService.insert(userInfo);
        if(result==1){
            return "注册成功！";
        }
        return "注册失败";
    }

    @ResponseBody
    @RequestMapping("/addRoleToUser")
    public ResponseEntity register(Integer uid, Integer roleId){

        return ResponseUtils.success(userInfoService.addRoleToUserById(uid,roleId));
    }

    @ResponseBody
    @RequestMapping("/api/getUserInfo")
    public ResponseEntity getUserInfo(String username){
       // redisUtils.set("userInfo", userInfoService.getUserAllInfoByUserName(username));
       // redisUtils.set("name","liuchao");
       // System.out.println("redisData:  "+ ((UserInfo)redisUtils.get("userInfo")).getPassword());
        //System.out.println(redisUtils.get("name"));
        return ResponseUtils.success(userInfoService.getUserAllInfoByUserName(username));
    }



    @RequestMapping("/403")
    public String unauthorizedRole(){
        System.out.println("------没有权限-------");
        return "403";
    }

    @RequestMapping("/management")
    public String management(){
        return "actuator";
    }

}
